/**
 * 
 */
package com.googlecode.pcapj;

import java.io.File;
import java.io.IOException;

/**
 * 
 */
public class DumpPackets {
	public static void main(String[] args) throws IOException {
		File file = new File("target/tcp.pcap");
		String filter = "tcp";
		
		file.getParentFile().mkdirs();
		
		PcapJ pcapJ = new PcapJ();
		Ethernet ethernet = new Ethernet();
		IPv4 ipv4 = new IPv4();
		TCP tcp = new TCP();
		ipv4.getTransportLayers().put(IPv4.Protocol.TCP, tcp);
		ethernet.getNeworkLayers().put(Ethernet.FramTypes.IP, ipv4);
		pcapJ.getDataLinkLayers().put(ethernet.getType(), ethernet);
		
		Interface inter = pcapJ.getAllInterface().get(0);
		inter.open();
		try{
			inter.setFilter(filter);
			DumpFileWriter dumpFileWriter = inter.openDumpFile(file);
			try{
				boolean existData = false;
				boolean noData = false;
				CapturedWriter capturedWriter = dumpFileWriter.read();
				for (int i = 0; i < 10; i++, capturedWriter = dumpFileWriter.read()) {
					Packet packet = capturedWriter.getPacket();
					System.out.println("" + packet);
					if (packet instanceof EthernetPacket) {
						EthernetPacket ethernetPacket = (EthernetPacket) packet;
						packet = ethernetPacket.getNetworkLayerPacket();
						System.out.println("  " + packet);
						if (packet instanceof IPv4Packet) {
							IPv4Packet ipv4Packet = (IPv4Packet)packet;
							System.out.println("  " + packet);
							packet = ipv4Packet.getTransportLayerPacket();
							System.out.println("    " + packet);
							if (packet instanceof TCPPacket) {
								TCPPacket tcpPacket = (TCPPacket) packet;
								byte[] data = tcpPacket.getData();
								System.out.println("    DataOffset:" + tcpPacket.getDataOffset());
								System.out.println("    BytesLength:" + tcpPacket.getBytes().length);
								System.out.println("    DataLength:" + data.length);
								if(data.length == 0 && !noData){
									capturedWriter.write();
									noData = true;
									
								}else if(!existData){
									capturedWriter.write();
									existData = true;
									
								}
							}
						}
					}
				}
			}finally{
				dumpFileWriter.close();
			}
			
		}finally{
			inter.close();	
		}
	}
}
